package com.swq.java.code.chapter19.code08;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CardLayoutDemo extends JFrame {
    private final String names[] = {"white", "red", "yellow"};
    private final Color colors[] = {Color.WHITE, Color.RED, Color.YELLOW};
    private JButton[] buttons = new JButton[3];
    private JPanel northPanel = new JPanel();
    private JPanel centerPanel = new JPanel();
    private JPanel[] cardPanels = new JPanel[3];
    private GridLayout gridLayout = new GridLayout(1, 3);
    private CardLayout cardLayout = new CardLayout();

    ActionListener listener = new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            JButton button = (JButton) event.getSource();
            cardLayout.show(centerPanel, button.getText());  //显示相应的卡
        }
    };

    public CardLayoutDemo(String title) {
        super(title);

        northPanel.setLayout(gridLayout);
        centerPanel.setLayout(cardLayout);
        for (int i = 0; i < buttons.length; i++) {
            buttons[i] = new JButton(names[i]);
            buttons[i].addActionListener(listener);
            northPanel.add(buttons[i]);

            cardPanels[i] = new JPanel();
            cardPanels[i].setBackground(colors[i]);
            centerPanel.add(cardPanels[i], names[i]);  //向centerPanel加入cardPanel
        }

        add(northPanel, BorderLayout.NORTH);
        add(centerPanel, BorderLayout.CENTER);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(250, 250);
        setVisible(true);
    }

    public static void main(String args[]) {
        new CardLayoutDemo("Hello");
    }
}

